package com.casa.POI.dianping;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Property;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;


public class FetchListPageUrlsExecutor extends CityExecutor {
	
	public FetchListPageUrlsExecutor(int cityId) {
		super(cityId);
	}
	
	@Override
	public void execute() {
		super.execute();
		ListSearchUrl searchUrl = this.getSearchUrl();
		int totalPage = this.getTotalPage(searchUrl.getUrl());
		Session s = SessionManager.getInstance().openSession();
		s.beginTransaction();
		searchUrl.setTotalPage(totalPage);
		s.update(searchUrl);
		for (int i = 0; i < totalPage; i++) {
			String url = String.format("%s?pg=%d", searchUrl.getUrl(), i + 1);
			ListPageUrl pageUrl = new ListPageUrl(url, searchUrl.getUrl(), getCityId());
			s.save(pageUrl);
			printStatus("add " + url);
		}
		s.getTransaction().commit();
		s.close();
	}
	
	private ListSearchUrl getSearchUrl() {
		Session s = SessionManager.getInstance().openSession();
		Criteria c = s.createCriteria(ListSearchUrl.class);
		c.add(Property.forName("cityId").eq(getCityId()));
		c.setMaxResults(1);
		ListSearchUrl searchUrl = (ListSearchUrl) c.uniqueResult();
		s.close();
		return searchUrl;
	}
	
	private int getTotalPage(String url) {
		while (true) {
			try {
				return fetchTotalPage(url);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	private int fetchTotalPage(String url) throws IOException, XPatherException {
		TagNode node = null;
		try {
			node = SpiderUtil.cleanUrl(url);
		} catch (FileNotFoundException e) {
			return 0;
		}
		Object[] results = node.evaluateXPath("/body/form//div[@class='box myListBox myList']/h1/strong");
		String text = ((TagNode) results[0]).getText().toString();
		Pattern p = Pattern.compile("\\d+");
		Matcher m = p.matcher(text);
		if (!m.find())
			throw new IllegalStateException();
		String countText = m.group();
		int count = Integer.parseInt(countText);
		return (int) Math.ceil(count / 20.0);
	}
	
	public static void main(String[] args) throws IOException, XPatherException {
		new FetchListPageUrlsExecutor(149).execute();
	}
}
